/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-19  @author lizhen
 */

package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
)

const (
	RequestBodyKey = "request-body"
)

func RequestBody(c *gin.Context) {
	body := c.Request.Body
	teed := newBuffer(body)
	if teed.err == nil {
		c.Set(RequestBodyKey, teed.content)
	}
	c.Request.Body = teed
}

type buffer struct {
	body    io.ReadCloser
	content []byte
	buffer  io.Reader
	err     error
}

func newBuffer(body io.ReadCloser) *buffer {
	b := &buffer{
		body: body,
	}
	if b.content, b.err = ioutil.ReadAll(body); b.err == nil {
		b.buffer = bytes.NewReader(b.content)
	}
	return b
}

func (b *buffer) Read(p []byte) (n int, err error) {
	if b.err != nil {
		err = b.err
		return
	}
	return b.buffer.Read(p)
}

func (b *buffer) Close() error {
	return b.body.Close()
}
